package com.jinkaimen.goodcash.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.retrofit.RequestUtils;
import com.ht.baselibs.retrofit.bean.RequestParam;
import com.ht.baselibs.retrofit.converter.fastjson.FastJsonConverterFactory;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.ui.widget.TitleBarView;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.DateUtils;
import com.ht.baselibs.utils.DeviceUtils;
import com.ht.baselibs.utils.LogUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;
import com.jinkaimen.goodcash.R;
import com.jinkaimen.goodcash.api.FileApi;
import com.jinkaimen.goodcash.constant.HttpConfig;
import com.jinkaimen.goodcash.thread.CompressPhotoThread;
import com.jinkaimen.goodcash.ui.weiget.dialog.CustomPopwindow;
import com.jinkaimen.goodcash.ui.weiget.dialog.DialogUtils;
import com.jinkaimen.goodcash.utils.PermissionUtils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;

public class IdentificationShopStep2Activity extends BaseActivity {

    private static final int REQUEST_CODE_TAKE_PHOTO_DOOR = 0;
    private static final int REQUEST_CODE_TAKE_PHOTO_DOOR_PHOTO = 3;
    private static final int REQUEST_CODE_TAKE_PHOTO_COUNTER = 1;
    private static final int REQUEST_CODE_TAKE_PHOTO_COUNTER_PHOTO = 4;
    private static final int REQUEST_CODE_TAKE_PHOTO_INDOOR = 2;
    private static final int REQUEST_CODE_TAKE_PHOTO_INDOOR_PHOTO = 5;

    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 0;
    private static final int MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD = 1;

    private static final String TAKE_PHOTO_PATH_DOOR = "ht/jkm/photo/STOREFRONT.jpg";
    private static final String TAKE_PHOTO_PATH_COUNTER = "ht/jkm/photo/COUNTER.jpg";
    private static final String TAKE_PHOTO_PATH_INDOOR = "ht/jkm/photo/INDOOR.jpg";

//    private TextView mStep1View;
//    private TextView mStep2View;
//    private TextView mStep3View;

    private ImageView mDoorView;
    private ImageView mCounterView;
    private ImageView mIndoorView;
    private boolean hasDoorImage;
    private boolean hasCounterImage;
    private boolean hasIndoorImage;
    private long mShopId;
    private long mUserId;
    private TextView mNextButton;
    private boolean mIsPublic;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected void initTitleBar() {
        mTitleBarView
                // TODO: 2017/6/16 此处版本1.1.3
                .setLeftBtnIcon(View.GONE)
                .setTitleText("填写店铺资料")

                .addActions(
                new TitleBarView.Action("上一步") {
                    @Override
                    public void performAction(View view) {
                        Bundle bundle = new Bundle();
                        bundle.putLong("report_shop_id", mShopId);
                        bundle.putBoolean("canEdit", true);
                        bundle.putLong("report_account_id", mUserId);
                        ActivityUtils.startActivityAndFinish(IdentificationShopStep2Activity.this, IdentificationShopStep1Activity.class, bundle);
                    }
                }
        );
    }

    @Override
    protected int initContentView() {
        return R.layout.activity_identification_shop_step2;
    }

    @Override
    protected void initIntentData(Intent callIntent) {
        mShopId = callIntent.getLongExtra("report_shop_id", 0);
        mUserId = callIntent.getLongExtra("report_account_id", 0);
        mIsPublic = callIntent.getBooleanExtra("isPublic", false);
    }

    @Override
    protected void initChildView() {
//        mStep1View = (TextView)findViewById(R.id.tv_header_identification_step1);
//        mStep2View = (TextView)findViewById(R.id.tv_header_identification_step2);
//        mStep3View = (TextView)findViewById(R.id.tv_header_identification_step3);

        mDoorView = (ImageView) findViewById(R.id.iv_activity_identification_shop_step2_door);
        mCounterView = (ImageView) findViewById(R.id.iv_activity_identification_shop_step2_counter);
        mIndoorView = (ImageView) findViewById(R.id.iv_activity_identification_shop_step2_indoor);
        mNextButton = (TextView) findViewById(R.id.btn_activity_identification_shop);

        Drawable drawable = getResources().getDrawable(R.mipmap.identification_step1_end);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//        mStep1View.setCompoundDrawables(drawable, null, null, null);
//        mStep2View.setEnabled(true);

    }

    @Override
    protected void initChildData() {
        String path = SharedPreferencesUtils.getString("take_photo_path_door" + mShopId, "");
        if (!TextUtils.isEmpty(path)) {
            hasDoorImage = true;
            Glide.with(this)//
                    .load(path)//
                    .skipMemoryCache(true)//
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(mDoorView);
        }
        String path1 = SharedPreferencesUtils.getString("take_photo_path_counter" + mShopId, "");
        if (!TextUtils.isEmpty(path1)) {
            hasCounterImage = true;
            Glide.with(this)//
                    .load(path1)//
                    .skipMemoryCache(true)//
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(mCounterView);
        }
        String path2 = SharedPreferencesUtils.getString("take_photo_path_indoor" + mShopId, "");
        if (!TextUtils.isEmpty(path2)) {
            hasIndoorImage = true;
            Glide.with(this)//
                    .load(path2)//
                    .skipMemoryCache(true)//
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .into(mIndoorView);
        }
    }

    @Override
    protected void setChildViewListener() {
        mNextButton.setClickable(true);
        mNextButton.setOnClickListener(this);
        mDoorView.setOnClickListener(this);
        mCounterView.setOnClickListener(this);
        mIndoorView.setOnClickListener(this);
    }

    private void takePicture(int requestCode) {
        String path = null;
        switch (requestCode) {
            case 0:
                path = TAKE_PHOTO_PATH_DOOR;
                DialogUtils.createPopwindow(IdentificationShopStep2Activity.this, "", "取消", new CustomPopwindow.OnBtnClickListener("拍照") {
                    @Override
                    public void onClick(CustomPopwindow popwindow, View view) {
                        try {

                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH_DOOR);

                            if (!file.getParentFile().exists()) {
                                file.getParentFile().mkdirs();
                            }
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                            startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO_DOOR);

                        } catch (Exception e) {
                            UIUtils.showToast("无法启用系统相机");
                            e.printStackTrace();
                        }

                    }
                }, new CustomPopwindow.OnBtnClickListener("从相册选择") {
                    @Override
                    public void onClick(CustomPopwindow popwindow, View view) {

                        Intent i = new Intent(
                                Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, REQUEST_CODE_TAKE_PHOTO_DOOR_PHOTO);
                    }
                }).showAtBottom(mTitleBarView);
                break;
            case 1:
//                path = TAKE_PHOTO_PATH_COUNTER;
                DialogUtils.createPopwindow(IdentificationShopStep2Activity.this, "", "取消", new CustomPopwindow.OnBtnClickListener("拍照") {
                    @Override
                    public void onClick(CustomPopwindow popwindow, View view) {
                        try {

                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH_COUNTER);

                            if (!file.getParentFile().exists()) {
                                file.getParentFile().mkdirs();
                            }
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                            startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO_COUNTER);

                        } catch (Exception e) {
                            UIUtils.showToast("无法启用系统相机");
                            e.printStackTrace();
                        }

                    }
                }, new CustomPopwindow.OnBtnClickListener("从相册选择") {
                    @Override
                    public void onClick(CustomPopwindow popwindow, View view) {

                        Intent i = new Intent(
                                Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, REQUEST_CODE_TAKE_PHOTO_COUNTER_PHOTO);
                    }
                }).showAtBottom(mTitleBarView);
                break;
            case 2:
//                path = TAKE_PHOTO_PATH_INDOOR;
                DialogUtils.createPopwindow(IdentificationShopStep2Activity.this, "", "取消", new CustomPopwindow.OnBtnClickListener("拍照") {
                    @Override
                    public void onClick(CustomPopwindow popwindow, View view) {
                        try {

                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            File file = new File(Environment.getExternalStorageDirectory(), TAKE_PHOTO_PATH_INDOOR);

                            if (!file.getParentFile().exists()) {
                                file.getParentFile().mkdirs();
                            }
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                            startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO_INDOOR);

                        } catch (Exception e) {
                            UIUtils.showToast("无法启用系统相机");
                            e.printStackTrace();
                        }

                    }
                }, new CustomPopwindow.OnBtnClickListener("从相册选择") {
                    @Override
                    public void onClick(CustomPopwindow popwindow, View view) {

                        Intent i = new Intent(
                                Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(i, REQUEST_CODE_TAKE_PHOTO_INDOOR_PHOTO);
                    }
                }).showAtBottom(mTitleBarView);
                break;
        }

//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        File file = new File(Environment.getExternalStorageDirectory(), path);
//
//        if (!file.getParentFile().exists()) {
//            file.getParentFile().mkdirs();
//        }
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
//        startActivityForResult(intent, requestCode);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.btn_activity_identification_shop:
                if (!hasDoorImage) {
                    UIUtils.showToast("门头照片为空");
                    return;
                }

                if (!hasCounterImage) {
                    UIUtils.showToast("收银台照片为空");
                    return;
                }

                if (!hasIndoorImage) {
                    UIUtils.showToast("店铺内景照片为空");
                    return;
                }

                showLoadingDialog();
                HashMap<String, Object> requestDataMap = new HashMap<>();
                requestDataMap.put("id", mShopId);
                requestDataMap.put("fileA", "STOREFRONT");
                requestDataMap.put("fileB", "COUNTER");
                requestDataMap.put("fileC", "INDOOR");
                String path1 = SharedPreferencesUtils.getString("take_photo_path_door" + mShopId, "");
                String path2 = SharedPreferencesUtils.getString("take_photo_path_counter" + mShopId, "");
                String path3 = SharedPreferencesUtils.getString("take_photo_path_indoor" + mShopId, "");
                File fileA = new File(path1);
                File fileB = new File(path2);
                File fileC = new File(path3);
                String requestData = JSON.toJSONString(requestDataMap, false);
                LogUtils.error(requestData);
                Map<String, RequestBody> params = RequestUtils.createPartMap(
                        new RequestParam("serviceCode", "INV_HSY001003"),
                        new RequestParam("requestData", requestData),
                        new RequestParam(HttpConfig.GlobalParam.APP_TYPE, "android"),
                        new RequestParam(HttpConfig.GlobalParam.V, "v1.6"),
                        new RequestParam(HttpConfig.GlobalParam.TIME_STAMP, DateUtils.getCurrentTime()),
                        new RequestParam(HttpConfig.GlobalParam.DEVICE_ID, DeviceUtils.getDeviceId() + ""),
                        new RequestParam("fileA", fileA),
                        new RequestParam("fileB", fileB),
                        new RequestParam("fileC", fileC)
                );
                Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                retrofitBuilder.client(builder.build())
                        .baseUrl(HttpConfig.BASE_URL) //这里的baseUrl不用设置
                        .addConverterFactory(FastJsonConverterFactory.create())
                        .build()
                        .create(FileApi.class).uploadFileAndForm(params).enqueue(new NetCallBack<String>() {
                    @Override
                    protected void onSuccess(Call<String> call, Response<String> response) {
                        Bundle bundle = new Bundle();
                        bundle.putLong("report_account_id", mUserId);
                        bundle.putLong("report_shop_id", mShopId);
                        bundle.putBoolean("isPublic", mIsPublic);
                        ActivityUtils.startActivityAndFinish(IdentificationShopStep2Activity.this, IdentificationShopStep3Activity.class, bundle);
                    }

                    @Override
                    protected boolean isNullNeedCallback() {
                        return true;
                    }

                    @Override
                    protected void hiddenProgress() {
                        hideLodingDialog();
                    }
                });
                break;
            case R.id.iv_activity_identification_shop_step2_door:
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture(REQUEST_CODE_TAKE_PHOTO_DOOR);
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }

                break;
            case R.id.iv_activity_identification_shop_step2_counter:
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture(REQUEST_CODE_TAKE_PHOTO_COUNTER);
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }

                break;
            case R.id.iv_activity_identification_shop_step2_indoor:
                if (PermissionUtils.hasCameraPermission()) {
                    if (PermissionUtils.hasWriteSDCardPermission()) {
                        takePicture(REQUEST_CODE_TAKE_PHOTO_INDOOR);
                    } else {
                        ActivityCompat.requestPermissions(this,
                                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                MY_PERMISSIONS_REQUEST_CALL_WRITE_SDCARD);
                    }
                } else {
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_CAMERA);
                }

                break;
        }
    }

    @Override
    protected void handleMessage(BaseActivity context, Message msg) {
        switch (msg.what) {
            case 200: //图片
                int type = (int) msg.obj;
                String path = "";
                ImageView distView = null;
                switch (type) {
                    case 0:
                        path = TAKE_PHOTO_PATH_DOOR;
                        distView = mDoorView;
                        hasDoorImage = true;
                        Glide.with(this)//
                                .load(Environment.getExternalStorageDirectory() + "/" + path)//
                                .skipMemoryCache(true)//
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .into(distView);
                        break;
                    case 1:
                        path = TAKE_PHOTO_PATH_COUNTER;
                        distView = mCounterView;
                        hasCounterImage = true;
                        Glide.with(this)//
                                .load(Environment.getExternalStorageDirectory() + "/" + path)//
                                .skipMemoryCache(true)//
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .into(distView);
                        break;
                    case 2:
                        path = TAKE_PHOTO_PATH_INDOOR;
                        distView = mIndoorView;
                        hasIndoorImage = true;
                        Glide.with(this)//
                                .load(Environment.getExternalStorageDirectory() + "/" + path)//
                                .skipMemoryCache(true)//
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .into(distView);
                        break;
                    case 3:
                        path = SharedPreferencesUtils.getString("take_photo_path_door" + mShopId, "");
                        distView = mDoorView;
                        hasDoorImage = true;
                        Glide.with(this)//
                                .load(path)//
                                .skipMemoryCache(true)//
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .into(distView);
                        break;
                    case 4:
                        path = SharedPreferencesUtils.getString("take_photo_path_counter" + mShopId, "");
                        distView = mCounterView;
                        hasCounterImage = true;
                        Glide.with(this)//
                                .load(path)//
                                .skipMemoryCache(true)//
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .into(distView);
                        break;
                    case 5:
                        path = SharedPreferencesUtils.getString("take_photo_path_indoor" + mShopId, "");
                        distView = mIndoorView;
                        hasIndoorImage = true;
                        Glide.with(this)//
                                .load(path)//
                                .skipMemoryCache(true)//
                                .diskCacheStrategy(DiskCacheStrategy.NONE)
                                .into(distView);
                        break;
                }

                hideLodingDialog();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String filePath = null;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_TAKE_PHOTO_DOOR:
                    filePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH_DOOR;
                    showLoadingDialog();
                    SharedPreferencesUtils.put("take_photo_path_door" + mShopId, filePath);
                    new CompressPhotoThread(mHandler, filePath, REQUEST_CODE_TAKE_PHOTO_DOOR).start();
                    break;
                case REQUEST_CODE_TAKE_PHOTO_DOOR_PHOTO:
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    new CompressPhotoThread(mHandler, picturePath, 3).start();
                    SharedPreferencesUtils.put("take_photo_path_door" + mShopId, picturePath);
                    showLoadingDialog();
                    break;
                case REQUEST_CODE_TAKE_PHOTO_COUNTER:
                    filePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH_COUNTER;
                    showLoadingDialog();
                    SharedPreferencesUtils.put("take_photo_path_counter" + mShopId, filePath);
                    new CompressPhotoThread(mHandler, filePath, REQUEST_CODE_TAKE_PHOTO_COUNTER).start();
                    break;
                case REQUEST_CODE_TAKE_PHOTO_COUNTER_PHOTO:
                    Uri selectedImage1 = data.getData();
                    String[] filePathColumn1 = {MediaStore.Images.Media.DATA};
                    Cursor cursor1 = getContentResolver().query(selectedImage1,
                            filePathColumn1, null, null, null);
                    cursor1.moveToFirst();
                    int columnIndex1 = cursor1.getColumnIndex(filePathColumn1[0]);
                    String picturePath1 = cursor1.getString(columnIndex1);
                    cursor1.close();
                    new CompressPhotoThread(mHandler, picturePath1, 4).start();
                    SharedPreferencesUtils.put("take_photo_path_counter" + mShopId, picturePath1);
                    showLoadingDialog();
                    break;
                case REQUEST_CODE_TAKE_PHOTO_INDOOR:
                    filePath = Environment.getExternalStorageDirectory() + "/" + TAKE_PHOTO_PATH_INDOOR;
                    showLoadingDialog();
                    SharedPreferencesUtils.put("take_photo_path_indoor" + mShopId, filePath);
                    new CompressPhotoThread(mHandler, filePath, REQUEST_CODE_TAKE_PHOTO_INDOOR).start();
                    break;
                case REQUEST_CODE_TAKE_PHOTO_INDOOR_PHOTO:
                    Uri selectedImage2 = data.getData();
                    String[] filePathColumn2 = {MediaStore.Images.Media.DATA};
                    Cursor cursor2 = getContentResolver().query(selectedImage2,
                            filePathColumn2, null, null, null);
                    cursor2.moveToFirst();
                    int columnIndex2 = cursor2.getColumnIndex(filePathColumn2[0]);
                    String picturePath2 = cursor2.getString(columnIndex2);
                    cursor2.close();
                    new CompressPhotoThread(mHandler, picturePath2, 5).start();
                    SharedPreferencesUtils.put("take_photo_path_indoor" + mShopId, picturePath2);
                    showLoadingDialog();
                    break;
            }
        }
    }

}
